//
//  CardToolViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/5.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SDWebImage

class CardToolViewController: KMViewController {

    fileprivate let cardToolId = "cardToolId"
    fileprivate let selectedId = "selectedId"
    
    fileprivate var tableView : UITableView!
    
    fileprivate var indexPath = 0 //当前cell
    
    fileprivate var titleArray = [shoppingUse,"",cardType,"",selectHobby,"",findRightCardForYou]
    fileprivate var dataArray = [[String]]()
    
    //参数数组
    var keyArray = [String]()
    
    init(title:String?) {
        super.init(nibName: nil, bundle: nil)
        
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        dataArray = [[shopping_title,business_title,other_title]]
        
        if tableView != nil {
            self.indexPath = 0
            keyArray.removeAll()
            tableView.reloadData()
        }
    }
    
    //MARK: 添加tableView
    fileprivate func createTableView() {
        
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CardToolCell.self, forCellReuseIdentifier: cardToolId)
        tableView.register(SelectedTypeCell.self, forCellReuseIdentifier: selectedId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension CardToolViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //tableView滑动到最底部
//        tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        
        if indexPath.row % 2 == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: cardToolId, for: indexPath) as? CardToolCell
            cell?.selectionStyle = .none
            cell?.toolDelegate = self
            cell?.titleLabel.text = titleArray[indexPath.row]
            
            if indexPath.row == 6 {
                
                let path = Bundle.main.path(forResource: "wait", ofType: "gif")
                let data = NSData.init(contentsOfFile: path!)
                let image = UIImage.sd_animatedGIF(with: data! as Data)
                
                //加载gif图片
                let gifView = UIImageView()
                gifView.image = image
                cell?.collectionView.addSubview(gifView)
                
                gifView.snp.makeConstraints { (make) in
                make.top.equalTo((cell?.titleLabel.snp.bottom)!).offset(RATIO_H(maxNum: 10))
                make.left.equalTo((cell?.titleLabel.snp.left)!).offset(RATIO(maxNum: 10))
                    make.width.equalTo(RATIO_H(maxNum: 150))
                    make.height.equalTo(RATIO_H(maxNum: 60))
                }
            }else{
                
                cell?.dataArray = dataArray[indexPath.row]
                cell?.collectionView.isUserInteractionEnabled = indexPath.row == self.indexPath
            }
            return cell!
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: selectedId, for: indexPath) as? SelectedTypeCell
            cell?.selectionStyle = .none
            cell?.titleLabel.text = dataArray[indexPath.row].first
            return cell!
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row % 2 == 0 {
            
            if indexPath.row == 6 {
                return RATIO_H(maxNum: 120)
            }else{
                //根据数组元素计算cell高度
                let count = dataArray[indexPath.row].count/2
                let count2 = Float(dataArray[indexPath.row].count)/2.0
                
                let sum = count2 > Float(count) ? count + 1 : count
                let height = RATIO_H(maxNum: 40) * CGFloat(sum) + RATIO_H(maxNum: 50)
                
                return height
            }
        }else{
            return RATIO_H(maxNum: 50)
        }
    }
    
}

extension CardToolViewController : CardToolCellDelegate {
    
    
    //MARK: 选择消费类型
    func selectType(title: String) {
        
        if self.indexPath > 6 {
            return
        }
        
        self.indexPath += 2
        let array = [title]
        self.dataArray.append(array)
        
        switch self.indexPath {
        case 2:
            self.dataArray.append([greatMoney,doubleScores,netWithName,greatYanValue])
        case 4:
        self.dataArray.append([food_title,tourism_title,cartoon_title,car_title,shopping_title,sport_title,moveMent,entertainment])
            self.keyArray.append(title)
        case 6:
            self.dataArray.append([String]())
            self.keyArray.append(title)
            self.navigationController?.pushViewController(CardDetailsViewController.init(keyArray: self.keyArray,title:self.title!), animated: true)
        default:
            break
        }
        
        self.tableView.reloadData()
    
        
    }
    
    
    
    
}



